#include "StdAfx.h"
#include "Properties.h"

namespace UTIL {

Properties::Properties(void)
{
}

Properties::Properties(LPCTSTR pszFileName)
{
	Load(pszFileName);
}

bool Properties::Load(LPCTSTR pszFileName)
{
	m_mapProperties.RemoveAll();

	File f;
	if (FAILED(f.Open(pszFileName)))
		return false;

	DWORD dwSize = f.GetSize();
	if (!dwSize)
		return true;

	CStringA strDataUTF8;
	if (!f.Read(strDataUTF8.GetBuffer(dwSize), dwSize))
		return false;

	strDataUTF8.ReleaseBuffer(f.GetNumberOfBytesRead());

    return ParseString(strDataUTF8);
}

bool Properties::ParseString(const CStringA &strDataUTF8)
{
	m_mapProperties.RemoveAll();

	// Parse

	CString strData(DecodeFromUTF8(strDataUTF8));

	for (int idx = -1; (idx = strData.Find( _T("\n") )) != -1; strData.Delete(0, idx + 1))
	{
		ATLASSERT(idx >= 0);

		if (idx <= 0)
			continue;

		ParseLine(strData.Left(idx));
	}

	// Add last value
	ParseLine(strData);

	return true;
}

void Properties::ParseLine(CString strLine)
{
	if (strLine.Trim().IsEmpty())
		return;

	if (strLine[0] == _T('#')) //comment
		return;

	int iSeparator = strLine.Find( _T('=') );
	if (iSeparator == -1)
		return;

	CString strKey = strLine.Left(iSeparator).Trim();
	if (strKey.IsEmpty())
		return;

	CString strValue;
	if (iSeparator+1 < strLine.GetLength())
		strValue = strLine.Mid(iSeparator+1).Trim();

	m_mapProperties[strKey] = strValue;
}

CString Properties::GetString(const CString &strKey) const
{
	CString strValue;
	if (!m_mapProperties.Lookup(strKey, strValue))
		return CString();

	return strValue;
}

int Properties::GetInt(const CString &strKey) const
{
	CString strValue;
	if (!m_mapProperties.Lookup(strKey, strValue))
		return 0;

	return _ttoi(strValue);
}

}; //namespace UTIL
